package com.dongdongshop.controller;


import com.dongdongshop.data.Result;
import com.dongdongshop.em.ResultEnum;
import com.dongdongshop.pojo.Admin;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginController {

    @RequestMapping("tologin")
    public String tologin() {
        return "login";
    }


    @RequestMapping("getLogin")
    @ResponseBody
    public Result getLogin(Admin admin) {
        //1.创建subject对象
        Subject subject = SecurityUtils.getSubject();
        //2.封装用户的账号密码  token对象
        UsernamePasswordToken token = new UsernamePasswordToken(admin.getName(), admin.getPassword());
        //3.执行登录功能

        //shiro是通过抛出异常的方式来提示账号不存在或者密码错误
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            //账号不存在
            return Result.response(ResultEnum.ERROR);
        }  catch (IncorrectCredentialsException e) {
            //密码错误
            return Result.response(ResultEnum.ERROR);
        }
        //登录成功
        return Result.response(ResultEnum.SUCCESS);
    }
}
